package com.va.yahooweather.commons;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class WoeidUtil
{
    private static WoeidUtil singletonInstance = null;

    public String searchLocation(String keyword) throws Exception
    {
        String id = "";
        HttpPost post = createHttpPost(keyword);
        HttpResponse response = getHttpPostResponse(post);
        String content = getResponseContent(response);
        id = parseWoeid(content);

        return id;
    }

    private String getResponseContent(HttpResponse response) throws IOException
    {
        String ret = "";

        HttpEntity entity = response.getEntity();

        if (entity != null)
        {
            InputStream is = entity.getContent();
            try
            {
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                byte[] buffer = new byte[1024];
                String line;
                while ((line = br.readLine()) != null)
                {
                    ret += line;
                }
            } finally
            {
                try
                {
                    is.close();
                } catch (Exception e)
                {
                }
            }
        }

        return ret;
    }

    private String parseWoeid(String content) throws DocumentException
    {
        String ret = "";
        String xml = "<root>" + content + "</root>";
        Document doc = new SAXReader().read(new ByteArrayInputStream(xml.getBytes()));
        Node firstRow = doc.selectSingleNode("//table/tbody/tr");
        List<Node> listTd = firstRow.selectNodes("//td");
        ret = listTd.get(3).getText();

        return ret;
    }

    private HttpResponse getHttpPostResponse(HttpPost httpPost) throws IOException
    {
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpPost);

        return response;
    }

    private HttpPost createHttpPost(String keyword) throws UnsupportedEncodingException
    {
        HttpPostBuilder postBuilder = new HttpPostBuilder();
        postBuilder.setMainURI(NetUtil.WOEID_SOURCE_LINK);
        postBuilder.putParam("action", NetUtil.WOEID_ACTION_VALUE);
        postBuilder.putParam("nonce", "755399355a");
        postBuilder.putParam("query", keyword);

        return postBuilder.encodedHttpPost();
    }

    public static WoeidUtil getInstance()
    {
        if (singletonInstance == null)
        {
            synchronized (WoeidUtil.class)
            {
                if (singletonInstance == null)
                {
                    singletonInstance = new WoeidUtil();
                }
            }
        }

        return singletonInstance;
    }
}
